package com.ctshk.common.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


/**
 * @author 谢诗宏
 * @description RSA非对称加密,以下公私钥是1024 bit PKCS#8格式
 * @date 2020-12-18
 */
public class RSAUtil {

    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDv/0eczt0twiP/x/cHBBlRq7EQ\n" +
            "ltVMOJNo3j5pLyFL+rfNpN6oKLnna9zk715itPEzxtmPSKt4egF29cexlCQCfcU2\n" +
            "0fq86lYXjPDHdoa+ajQ9R0a8JRedRagM6c7zVHbYI1gTyGsIXUUgoDxyAgFem3P2\n" +
            "TmLR95zC4QyzRQ1LVQIDAQAB";
    private static final String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAO//R5zO3S3CI//H\n" +
            "9wcEGVGrsRCW1Uw4k2jePmkvIUv6t82k3qgouedr3OTvXmK08TPG2Y9Iq3h6AXb1\n" +
            "x7GUJAJ9xTbR+rzqVheM8Md2hr5qND1HRrwlF51FqAzpzvNUdtgjWBPIawhdRSCg\n" +
            "PHICAV6bc/ZOYtH3nMLhDLNFDUtVAgMBAAECgYAsFGINzfzXu7Gq+ApKEpmn43X5\n" +
            "CwsQHdANUcx6uzpNXzZFIgP3NMu4UppWvhRC4uLuVJZ+96Tu0tHUDJ5p4kCejXWf\n" +
            "0e2A3H8r284tA1OTkFdrn6fP6GXv/F0wbA8WSlh4MM5dGx+shQOmtV3vFfJpIgwX\n" +
            "78Alf3IO4jGnZ6/BAQJBAPsyklDVDLecmLezbjzAz32yX1ECc3FDi5PrRGPPpl19\n" +
            "10HCZC62NPxAw/521YThvcx9cDFOFAMeFF2gixS+ukECQQD0leP/jk8Re34L6xa1\n" +
            "8W2eHVs6Oq4lKuWvVJjba0UFzSjAm58bh4hwIoEQLjJNJ3lpK7GRIy1zBrQJocKg\n" +
            "vwQVAkEA8yQJIfqGO7d0zuL7wgxzCly8DAKOUUSq9rtT0DSu+HGVCI6rP9eXw87A\n" +
            "py7JD70dZLDKBr9neXkFB3cdCDBwwQJBALOP/6002xOoqCcz1p6IusNkJf+f6Q3c\n" +
            "anfIEdi07h2OOyb8mVjqrd41Vq98Wu2N13LA40H8o3dZKoAPxAWjdukCQQCkKNkB\n" +
            "j+yFU4RLu1yYnwr7yIvERchXjobbR8dr2jL8brIeGI9UCZaxI9HC4UcD2PXo9qmz\n" +
            "92A2+kuxOhNsymR/";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";


    private static final RSA rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "1344284713337857");
        jsonObject.put("username", "admin1");
        jsonObject.put("nickname", "管理员");
        jsonObject.put("avatar", "xxxxxxxx");
        jsonObject.put("gmtModified", "2020-12-18 11:01:18");

        String e = encryptStr(jsonObject.toJSONString());
        System.out.println(e);
        String d = decryptStr(e);
        System.out.println(d);
    }

    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptStr(String data) {
        return rsa.encryptBase64(data, KeyType.PublicKey);
    }

    /**
     * 解密
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptStr(String data) {
        return rsa.decryptStr(data, KeyType.PrivateKey);
    }

    public static String encryptByPublicKey(String content, String publicKey) throws Exception {
        return URLEncoder.encode(new String(Base64.getEncoder().encode(encryptByPublicKey(content.getBytes(StandardCharsets.UTF_8), getPublicKey(publicKey)))),"UTF-8");

    }

    /**
     * 公钥加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        subsection(data,cipher,out, MAX_ENCRYPT_BLOCK);
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 公钥字符串转PublicKey实例
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    public static String decryptByPrivateKey(String content, String privateKey) throws Exception {

        return new String(decryptByPrivateKey(Base64.getDecoder().decode(URLDecoder.decode(content,"utf-8")), getPrivateKey(privateKey)), StandardCharsets.UTF_8);
    }

    /**
     * 私钥字符串转PrivateKey实例
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 私钥解密
     * @param encryptedData
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        subsection(encryptedData,cipher,out,MAX_DECRYPT_BLOCK);
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    private static void subsection (byte[] data,Cipher cipher,ByteArrayOutputStream out,int bock) throws Exception{
        int inputLen = data.length;
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > bock) {
                cache = cipher.doFinal(data, offSet, bock);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * bock;
        }
    }

    /**
     * RSA签名
     * @param content 待签名数据
     * @param privateKey 商户私钥
     * @return 签名值
     */
    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            byte[] signed = signature.sign();
            return URLEncoder.encode(Base64.getEncoder().encodeToString(signed), "utf-8");
        } catch (Exception ignored) {

        }
        return null;
    }

}
